<template>
  <div class="body">
    <el-card>
      <div class="top">
        <el-form
          :model="ruleFormTop"
          :rules="rulesTop"
          ref="ruleFormTop"
          label-width="100px"
          class="demo-ruleForm"
        >
          <div class="examinationNum">
            <el-form-item label="名称：" prop="subsectionName">
              <el-input
                v-model="ruleFormTop.subsectionName"
                placeholder="请输入名称"
              ></el-input>
            </el-form-item>
          </div>
          <el-form-item label="年级：" prop="gradeName">
            <el-select
              v-model="ruleFormTop.gradeName"
              @change="changeGrade"
              placeholder="请选择年级"
            >
              <el-option
                v-for="(item, index) in gradeOptions"
                :key="index"
                :label="item.typeName"
                :value="{value:item.typeId,label:item.typeName}"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学科：" prop="subjectName">
            <el-select
              v-model="ruleFormTop.subjectName"
              @change="changeSubject"
              placeholder="请选择学科"
            >
              <el-option
                v-for="(item, index) in subjectOptions"
                :key="index"
                :label="item.typeName"
                :value="{value:item.typeId,label:item.typeName}"

              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="难度：" prop="difficultyName">
            <el-select
              v-model="ruleFormTop.difficultyName"
              @change="changeDifficulty"
              placeholder="请选择学科"
            >
              <el-option
                v-for="(item, index) in options1"
                :key="index"
                :label="item.typeName"
                :value="{value:item.typeId,label:item.typeName}"

              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="bufen">
        <el-button size="small" type="primary" @click="addSubsection"
          >添加部分</el-button
        >
        <el-button size="small" @click="removeCheck">批量删除</el-button>
        <div class="part">
          <el-form
            v-for="(item, index) in subsection"
            :key="index"
            ref="ruleForm"
            :model="item"
          >
            <div class="flex1">
              <div class="flex">
                <el-checkbox type="checkout" class="checkbox" v-model="item.checked" @change="checkedChange"></el-checkbox>
                <div style="width: 100px">第{{ index + 1 }}部分</div>
                <div style="width: 200px">
                  <el-input
                    v-model="item.titleName"
                    class="inp"
                    placeholder="请输入描述"
                  />
                </div>
              </div>
              <div>
                <el-button size="small" type="primary" @click="addPart(index)"
                  >添加试题</el-button
                >
                <el-button
                  size="small"
                  :disabled="subsection.length == 1"
                  @click="delPart(index)"
                  >删除试题</el-button
                >
                <span class="fen">总分 :{{ item.total }}</span>
                <el-button size="small">收起</el-button>
              </div>
            </div>
            <div class="tips">
              <div class="content">
                <el-input
                  v-model="item.describe"
                  placeholder="请输入名称"
                ></el-input>
                <!-- 本部分共<span
                  v-for="(
                    questionListItem, questionListIndex
                  ) in item.questionList"
                  :key="questionListIndex"
                  >{{ questionListItem.number }} 个小题,每小题{{
                    questionListItem.number * questionListItem.score
                  }}分,</span
                >
                共计分;在每小题给出的选项中,仅有一项是符合题目要求的。 -->
              </div>
            </div>
            <div
              class="question"
              v-for="(ite, ind) in item.testing"
              :key="ind"
            >
              <div class="questions">
                <el-form-item
                  :prop="'testing.' + ind + '.questions'"
                  :rules="rules.questions"
                >
                  <el-select v-model="ite.questions" placeholder="请选择题库">
                    <el-option
                      v-for="item in options"
                      :key="item.type"
                      :label="item.typeName"
                      :value="item.type"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  :prop="`testing[${ind}].difficulty`"
                  :rules="rules.difficulty"
                >
                  <el-select v-model="ite.difficulty" placeholder="请选择难度">
                    <el-option
                      v-for="item in options1"
                      :key="item.typeId"
                      :label="item.typeName"
                      :value="item.typeId + ''"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item
                  :prop="'testing.' + ind + '.number'"
                  :rules="rules.number"
                >
                   <el-input v-model="ite.number" @blur="changeTotalscore1(index)"  placeholder="请选择数量" />
                </el-form-item>
                <el-form-item
                  :prop="'testing.' + ind + '.score'"
                  :rules="rules.score"
                >
                  <el-input
                    v-model="ite.score"
                    class="inp"
                    placeholder="请设置分数"
                    type="number"
                    @blur="changeTotalscore(index)"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button size="small" @click="delIte(index, ind)"
                    >删除</el-button
                  >
                </el-form-item>
              </div>
            </div>
          </el-form>
        </div>
      </div>
      <div class="buttons">
        <el-button @click="signOut">退出</el-button>
        <el-button type="primary" @click="submitForm">完成</el-button>
      </div>
    </el-card>
  </div>
</template>
<script>
import {
  getQuertionBankListApi,
  getGradeListApi,
  // getCourseListApi,
} from "@/api/onlinehomework/questionbank.js";
import {
  getSubsectionRulesDataApi,
  addSubsectionRulesItemApi,
  EditSubsectionRulesItemApi,
  getDifficultyApi
} from "@/api/onlinehomework/subsectionRules.js";
export default {
  data() {
    return {
      options: [
        {
            type:'0',
            typeName:'单选题'
        },
        {
            type:'1',
            typeName:'多选题'
        },
        {
            type:'2',
            typeName:'判断题'
        },
        {
            type:'3',
            typeName:'填空题'
        },
        {
            type:'4',
            typeName:'简答题'
        },
      ],
      options1: [],
      options2: [
        // {
        //   value: "1",
        //   label: "2道",
        // },
        // {
        //   value: "2",
        //   label: "3道",
        // },
        // {
        //   value: "3",
        //   label: "5道",
        // },
      ],
      subsection: [
        {
          describe:'', // 部分文字提示
          titleName: "",
          total: 0,
          // show: true,
          checked:false,
          difficulty: "",
          testing: [
            {
              questions: "",
              difficulty: "",
              number: "",
              score: "",
            },
          ],
        },
      ],
      rules: {
        titleName: [{ required: true, message: "请输入描述", trigger: "blur" }],
        score: [{ required: true, message: "请设置分数", trigger: "blur" }],
        testing: [{ required: true, message: "请选择科目", trigger: "change" }],
        difficulty: [
          { required: true, message: "请选择难度", trigger: "change" },
        ],
        number: [{ required: true, message: "请选择数量", trigger: "change" }],
      },
      difficultyOptions: [], //难度数据
      subjectOptions: [], //学科数据
      gradeOptions: [], //年级数据
      ruleFormTop: {
        subsectionName: "", // 试卷名称
        gradeName: "", // 年级
        subjectName: "", // 学科
        subjectId:'',
        gradeId:'',
        difficultyId:'',
        difficultyName:''
      },
      rulesTop: {
        subsectionName: [
          { required: true, message: "请输入名称", trigger: "blur" },
        ],
        gradeName: [{ required: true, message: "请选择年级", trigger: "blur" }],
        subject: [{ required: true, message: "请选择科目", trigger: "change" }],
      },
      filterGradeName:'',
      checkedArr:[]
    };
  },
  // computed:{
  //   getTotal() {
  //     let a
  //     this.subsection.forEach(item=>{
  //       item.testing.forEach((it)=>{
  //         a += Number(it.number) * Number(it.score)
  //       })
  //     })
  //     return a
  //   }
  // },
  mounted() {
    this.getQuertionBankData();
    this.getCourseData();
    this.getGradeData();
    console.log(this.$route.params);
    this.getSubsectionRulesData();
    
    getGradeListApi({ parentId: 158 }).then((res) => {
      console.log(res);
      this.options1 = res.rows
    });
    if (this.$route.params.isEdit == "1") {
      getSubsectionRulesDataApi({pageSize:'10',pageNum:this.$route.params.currentPage}).then(res=>{
        console.log(res);
        console.log(this.$route.params);
        let filterItem = res.rows.filter(item=>{
          console.log(item);
          return item.id == this.$route.params.row
        })
        console.log(filterItem);
        this.subsection = filterItem[0].title ? JSON.parse(filterItem[0].title) : this.subsection 
        this.ruleFormTop.subsectionName = filterItem[0].paperName
        this.ruleFormTop.subjectName = filterItem[0].subjectName
        this.ruleFormTop.gradeName = filterItem[0].gradeName
        this.ruleFormTop.difficultyName = filterItem[0].difficultyName
      })
       
    }
  },
  methods: {
    checkedChange(val) {
      console.log(val);
      // this.subsection.push(val)
      // this.subsection
    },
    removeCheck() {
      let filterItem = this.subsection.filter(item=>{
        return !item.checked
      })
      this.subsection = filterItem
    },
    signOut() {
      this.$router.push({
        path:"/onlinehomework/testpaper/subsectionrules"
      })
    },
    async getSubsectionRulesData() {
      const data = await getSubsectionRulesDataApi();
      console.log(data);
      // data.rows.forEach((item) => {

      //   // if (item.difficulty == "1") {
      //   //   item.difficultyText = "容易";
      //   // } else if (item.difficulty == "2") {
      //   //   item.difficultyText = "简单";
      //   // } else if (item.difficulty == "3") {
      //   //   item.difficultyText = "普通";
      //   // } else if (item.difficulty == "4") {
      //   //   item.difficultyText = "困难";
      //   // } else if (item.difficulty == "5") {
      //   //   item.difficultyText = "超难";
      //   // }
      // });
      // this.options1 = data.rows;
      // console.log(this.options1);
    },

    // 年级
    async getGradeData() {
      const data = await getGradeListApi({ parentId: 55 });
      this.gradeOptions = data.rows;
    },
    //  学科
    async getCourseData() {
      const data = await getDifficultyApi({ parentId: 130 });
      this.subjectOptions = data.rows;
    },
    // 题库
    async getQuertionBankData() {
      const data = await getQuertionBankListApi()
      console.log(data);
      // this.options = data.rows
      // this.options.forEach(item=>{
      //   if(item.questionsType == '0') {
      //       item.questionsTypeClone = '单选题'
      //   }else if(item.questionsType == '1') {
      //       item.questionsTypeClone = '多选题'
      //   }else if(item.questionsType == '2') {
      //       item.questionsTypeClone = '判断题'
      //   }else if(item.questionsType == '3') {
      //       item.questionsTypeClone = '填空题'
      //   }else if(item.questionsType == '4') {
      //       item.questionsTypeClone = '简答题'
      //   }
      // })
    },

    // 年级
    changeGrade(obj) {
      // this.filterGradeName = obj.la;
      this.ruleFormTop.gradeId = obj.value
      this.ruleFormTop.gradeName = obj.label
    },
    // 学科
    changeSubject(obj) {
      this.ruleFormTop.subjectId = obj.value
      this.ruleFormTop.subjectName = obj.label
    },
    changeDifficulty(obj) {
      this.ruleFormTop.difficultyId = obj.value
      this.ruleFormTop.difficultyName = obj.label
    },
    //   提交
    submitForm() {
      console.log(this.ruleFormTop);
      let arr = [];
      this.$refs["ruleFormTop"].validate((v) => {
        console.log(v, "---------------");
      });
      this.$refs.ruleForm.forEach((item) => {
        item.validate((valid) => {
          arr.push(valid);
        });
      });
      let sub = arr.every((item) => {
        return item;
      });
      let obj = {
              paperName:this.ruleFormTop.subsectionName,
              subjectName:this.ruleFormTop.subject,
              gradeName:this.ruleFormTop.gradeName,
              title:this.subsection
            }
            console.log(obj,'------obj');
      if (sub) {
       
          if(this.$route.params.isEdit == '0') {
            let obj = {
              paperName:this.ruleFormTop.subsectionName,
              subjectId:this.ruleFormTop.subjectId,
              subjectName:this.ruleFormTop.subjectName,
              gradeName:this.ruleFormTop.gradeName,
              gradeId:this.ruleFormTop.gradeId,
              title:this.subsection,
              difficultyName:this.ruleFormTop.difficultyName,
              difficultyId:this.ruleFormTop.difficultyId
            }
            console.log(obj,'------obj');
            addSubsectionRulesItemApi(obj).then(res=>{
              console.log(res);
              if(res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '添加成功',
                });
                this.$router.push({
                  path:"/onlinehomework/testpaper/subsectionrules"
                })
              }else {
                this.$message({
                  type: 'error',
                  message: '添加失败',
                });
                this.$router.push({
                  path:"/onlinehomework/testpaper/subsectionrules"
                })
              }
            })
          }else {
             let obj = {
              paperName:this.ruleFormTop.subsectionName,
              subjectId:this.ruleFormTop.subjectId,
              subjectName:this.ruleFormTop.subjectName,
              gradeName:this.ruleFormTop.gradeName,
              gradeId:this.ruleFormTop.gradeId,
              title:this.subsection,
              difficultyName:this.ruleFormTop.difficultyName,
              difficultyId:this.ruleFormTop.difficultyId,
              id:this.$route.params.row
            }
            console.log(obj);
            let obj1 = {};
            for (let key in obj) {
              if (
                (obj[key] === 0 || obj[key]) &&
                obj[key].toString().replace(/(^\s*)|(\s*$)/g, "") !== ""
              ) {
                // 保存属性
                obj1[key] = obj[key];
              }
            }
            EditSubsectionRulesItemApi(obj1).then(res=>{
              console.log(res);
              if(res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '修改成功',
                });
                this.$router.push({
                  path:"/onlinehomework/testpaper/subsectionrules"
                })
              }else {
                this.$message({
                  type: 'error',
                  message: '修改失败',
                });
                this.$router.push({
                  path:"/onlinehomework/testpaper/subsectionrules"
                })
              }
            })
          }
      } else {
        return false;
      }
    },
    changeTotalscore1(index) {
      this.changeTotalscore(index)
    },
    //   计算总分
    changeTotalscore(index) {
      console.log(index);
      this.subsection[index].total = 0;
      this.subsection[index].testing.forEach((item) => {
        let a = Number(item.number) * Number(item.score)
        this.subsection[index].total += a
        // console.log(Number(item.number));
        // console.log(this.a);
        // this.subsection[index].total = Number(item.number * item.fraction)
      });
    },
    //   删除部分
    delIte(index, ind) {
      this.$confirm("此操作将永久删除该试题, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.subsection[index].testing.splice(ind, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //   删除试题
    delPart(index) {
      this.$confirm("此操作将永久删除该部分, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.subsection.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //   添加试题
    addPart(index) {
      this.subsection[index].testing.push({
        questions: "",
        difficulty: "",
        number: "",
        score: "",
      });
    },
    //   添加部分
    addSubsection() {
      let obj = {
        titleName: "",
        total: 0,
        checked:false,
        testing: [
          {
            questions: "",
            difficulty: "",
            number: "",
            score: "",
          },
        ],
      }
      this.subsection.push(obj);
    },
  },
  created() {},
  // computed: {},
  watch: {},
};
</script>
<style lang="scss" scoped>
.flex {
  display: flex;
  align-items: center;
  .checkbox{
    margin-right: 10px;
  }
}
.flex1 {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-right: 40px;
}
.body {
  width: 100%;
  min-width: 100vh;
  padding: 0 20px;
  .top {
    width: 100%;
    .examinationNum .el-input {
      width: 221px;
    }
  }
  .fen {
    margin-left: 10px;
    width: 80px;
    height: 32px;
    line-height: 32px;
    display: inline-block;
  }
  .buttons {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 80px;
  }
  .part {
    width: 100%;
    border: 1px solid #f6f6f6;
    margin-top: 12px;
    padding: 10px 40px;
    .question {
      width: 100%;
      padding-right: 40px;
      margin-top: 12px;
      box-sizing: border-box;
      .questions {
        padding: 20px;
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        border: 1px solid #f6f6f6;
        ::v-deep .el-form-item {
          margin-bottom: 0px;
        }
        .tiku {
          height: 50px;
          display: flex;
          align-items: center;
          padding: 10px;
          box-sizing: border-box;
          width: 100%;
          border: 1px solid #ddd;
          border-radius: 5px;
          .conts {
            width: 100px;
            height: 25px;
            line-height: 25px;
            text-align: center;
            border: 1px solid #eee;
            border-radius: 3px;
          }
        }
        .tikus {
          border-radius: 5px;
          height: 50px;
          width: 100%;
          border: 1px solid #ddd;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }

    .tips {
      margin-left: 100px;
      height: 40px;
      line-height: 40px;
      padding-right: 40px;
      margin-top: 12px;
      box-sizing: border-box;
      .content {
        width: 300px;
        // background-color: #f0f8ff;
        padding-left: 10px;
      }
    }
  }
}
</style>
